package com.ruoyi.web.controller.pc.user;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.blogs.domain.BsNote;
import com.ruoyi.blogs.domain.BsNoteLikeRecord;
import com.ruoyi.blogs.service.IBsNoteLikeRecordService;
import com.ruoyi.blogs.service.IBsNoteService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.IdUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@Api(tags = "博客文章")
@RestController
@RequestMapping("/user/note")
public class UserNoteController extends BaseController {
    @Autowired
    private IBsNoteService bsNoteService;

    @Autowired
    private IBsNoteLikeRecordService bsNoteLikeRecordService;

    /**
     * 新增笔记管理
     */
    @ApiOperation("发布博客文章")
    @Transactional
    @PostMapping
    public R<Integer> add(@RequestBody BsNote bsNote) {
        bsNote.setId(IdUtils.fastSimpleUUID());
        bsNote.setVisible(0);
        bsNote.setIsOfficialRecommend(0);
        bsNote.setIsHot(0);
        bsNote.setIsHome(0);
        return R.ok(bsNoteService.insertBsNote(bsNote));
    }

    /**
     * 笔记点赞或取消点赞
     */
    @ApiOperation("博客文章点赞或取消点赞")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "文章id", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "value", value = "0是取消点赞，1是点赞", dataType = "Integer", dataTypeClass = Integer.class),
    })
    @Transactional
    @PostMapping("/like")
    public R<String> like(@RequestParam("id") String id, Integer value) {
        Map<String, Object> map = new HashMap<>();
        map.put("id",id);
        map.put("value",value);
        bsNoteService.updateBsNoteLike(map);
        BsNoteLikeRecord bsNoteLikeRecord = new BsNoteLikeRecord();
        bsNoteLikeRecord.setNoteId(id);
        if(value == 1){
            // 点赞
            bsNoteLikeRecord.setId(IdUtils.fastSimpleUUID());
            bsNoteLikeRecordService.insertBsNoteLikeRecord(bsNoteLikeRecord);
        } else {
            // 取消点赞
            bsNoteLikeRecord.setUserId(SecurityUtils.getUserId());
            bsNoteLikeRecordService.deleteBsNoteLikeRecordByQuery(bsNoteLikeRecord);
        }
        return R.ok();
    }
}
